package smartq.app;

import com.app.smart_q.R;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class DB_test extends Activity implements View.OnClickListener ,AdapterView.OnItemClickListener {
	
	EditText etPersonName;
	Button btnAddPerson;
	ListView list;
	
	InfoDBHelper dbHelper;
	SQLiteDatabase db;
	Cursor cursor;
	SimpleCursorAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.testdb);
		
		etPersonName = (EditText) findViewById(R.id.person_name);
		btnAddPerson = (Button) findViewById(R.id.add_button);
		btnAddPerson.setOnClickListener(this);
		
		list = (ListView) findViewById(R.id.list);
		list.setOnItemClickListener(this);
		
		dbHelper = new InfoDBHelper(this);
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void onResume(){
		super.onResume();
		db = dbHelper.getWritableDatabase();
		String[] queryColum =new String[] {
			"_id",InfoDBHelper.TABLE_KEY_NAME,InfoDBHelper.TABLE_KEY_PHONE};
		
		cursor = db.query(InfoDBHelper.TABLE_NAME, queryColum, null, null, null, null, null);
		
		String[] showColumns = new String[] {InfoDBHelper.TABLE_KEY_NAME,InfoDBHelper.TABLE_KEY_PHONE};
		
		int[] views = new int[] {android.R.id.text1,android.R.id.text2};
		adapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, cursor, showColumns, views);
		list.setAdapter(adapter);
	}
	
	@Override
	public void onPause(){
		super.onPause();
		cursor.close();
		db.close();
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void onItemClick(AdapterView<?> parent, View v ,int position ,long id){
		cursor.moveToPosition(position);
		String rowId = cursor.getString(0);
		db.delete(InfoDBHelper.TABLE_NAME, "_id = ?", new String[] {rowId});
		cursor.requery();
		adapter.notifyDataSetChanged();
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View v){
		ContentValues cv = new ContentValues();
		cv.put(InfoDBHelper.TABLE_KEY_NAME, "222");
		cv.put(InfoDBHelper.TABLE_KEY_PHONE, etPersonName.getText().toString());
		db.insert(InfoDBHelper.TABLE_NAME, null, cv);
		cursor.requery();
		adapter.notifyDataSetChanged();
		etPersonName.setText(null);
	}

	
	
}
